package com.liujit.standard.basis.core.util;

import cn.hutool.core.io.IoUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.Charset;

/**
 * @description: 请求上下文工具类
 * @author: liujun
 * @create: 2020/12/31 4:52 下午
 **/
@Slf4j
public class ReqUtil {


    /**
     * 获取request
     *
     * @return
     */
    public static HttpServletRequest getRequest() {
        HttpServletRequest req = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        return req;
    }

    /**
     * 获取response
     *
     * @return
     */
    public static HttpServletResponse getResponse() {
        HttpServletResponse resp = ((ServletWebRequest) RequestContextHolder.getRequestAttributes()).getResponse();
        return resp;
    }

    /**
     * 获取request body
     *
     * @param request
     * @return
     */
    public static String getRequestBody(HttpServletRequest request) {
        try {
            return IoUtil.read(request.getInputStream(), Charset.forName("UTF-8"));
        } catch (IOException e) {
            log.error(e.getMessage());
        }
        return "";
    }

    /**
     * 获取header
     *
     * @param headerKey
     * @return
     */
    public static String getHeader(String headerKey) {
        return getRequest().getHeader(headerKey);
    }

}
